package hyl.dao;

import hyl.entity.User;

import java.sql.*;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2022/6/14 10:10
 **/
public class UserDaoImpl extends BaseDao implements UserDao {
	@Override
	public User login(String name){
		User user = null;
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			//2创建连接
			conn = getConnection();
			//3编写sql
			String sql ="Select * from user where userid=?";
			//4创建执行对象
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, name);
			//5、执行
			rs = pstm.executeQuery();
			//6、处理结果
			while (rs.next()){
				user = new User( rs.getInt("id"),
						rs.getString("userId"),
						rs.getString("password"),
						rs.getString("nickname"),
						rs.getString("image"),
						rs.getString("sex"),
						rs.getString("name"));
			}
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}finally {
			//7、释放资源
			closeAll(rs,pstm,conn);
		}
		return user;
	}

	@Override
	public int add(User user) {
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			//2创建连接
			conn = getConnection();
			//3编写sql
			String sql ="insert into user(userid,password,nickname,address,createtime) values(?,?,?,?,NOW()) ";
			//4创建执行对象
			pstm = conn.prepareStatement(sql);
			pstm.setString(1,user.getUserId() );
			pstm.setString(2,user.getPassword() );
			pstm.setString(3,user.getNickname());
			pstm.setString(4,user.getAddress() );
			//5、执行
			return  pstm.executeUpdate();
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}finally {
			//7、释放资源
			closeAll(rs,pstm,conn);
		}
		return 0;
	}
}
